import { onMounted, ref } from "vue";
import {
  type ButtonsCallBackParams,
  type PageInfo,
  type PlusColumn,
  useTable
} from "plus-pro-components";
import { ElMessage, ElMessageBox } from "element-plus";
import { api } from "@/api/notifyInfo";
import { WarnTriangleFilled } from "@element-plus/icons-vue";
import { NotifyStatusEnum } from "@/model/enums";

export function useEntNotifyInfo() {
  const isAdd = ref(false);

  // ========= search form =========

  // 查询表单对象
  const searchFormData = ref({
    appId: "",
    apiName: "",
    apiVersion: "",
    notifyStatus: "",
    pageIndex: 1,
    pageSize: 10
  });

  // 查询表单字段定义
  const searchFormColumns: PlusColumn[] = [
    {
      label: "AppId",
      prop: "appId"
    },
    {
      label: "接口名称",
      prop: "apiName"
    },
    {
      label: "接口版本",
      prop: "apiVersion"
    },
    {
      label: "状态",
      prop: "notifyStatus",
      width: 80,
      valueType: "select",
      options: [
        {
          label: "成功",
          value: NotifyStatusEnum.SUCCESS,
          color: "green"
        },
        {
          label: "失败",
          value: NotifyStatusEnum.FAIL,
          color: "red"
        },
        {
          label: "重试结束",
          value: NotifyStatusEnum.END,
          color: "gray"
        }
      ]
    }
  ];

  // ========= table =========

  // 表格对象
  const {
    tableData,
    total,
    pageInfo,
    buttons: actionButtons
  } = useTable<any[]>();
  // 默认每页条数,默认10
  pageInfo.value.pageSize = 10;

  // 表格字段定义
  const tableColumns: PlusColumn[] = [
    {
      label: "AppId",
      prop: "appId"
    },
    {
      label: "接口名称",
      prop: "apiName"
    },
    {
      label: "接口版本",
      prop: "apiVersion"
    },
    {
      width: 120,
      label: "最近一次发送时间",
      prop: "lastSendTime"
    },
    {
      width: 120,
      label: "下一次发送时间",
      prop: "nextSendTime"
    },
    {
      label: "已发送次数",
      prop: "sendCnt"
    },
    {
      label: "发送内容",
      prop: "content"
    },
    {
      label: "状态",
      prop: "notifyStatus",
      width: 100,
      valueType: "select",
      options: [
        {
          label: "成功",
          value: NotifyStatusEnum.SUCCESS,
          color: "green"
        },
        {
          label: "失败",
          value: NotifyStatusEnum.FAIL,
          color: "red"
        },
        {
          label: "重试结束",
          value: NotifyStatusEnum.END,
          color: "gray"
        },
        {
          label: "重试结束",
          value: NotifyStatusEnum.STOP,
          color: "gray"
        }
      ]
    },
    {
      label: "失败原因",
      prop: "errorMsg"
    },
    {
      label: "返回结果",
      prop: "resultContent",
      width: 120
    },
    {
      label: "备注",
      prop: "remark"
    },
    {
      width: 120,
      label: "添加时间",
      prop: "addTime"
    },
    {
      width: 120,
      label: "修改时间",
      prop: "updateTime"
    }
  ];
  // 表格按钮定义
  actionButtons.value = [
    {
      text: "推送",
      props: {
        type: "primary"
      },
      onClick(params: ButtonsCallBackParams) {
        ElMessageBox.prompt("回调URL", "推送", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          inputPlaceholder: "【选填】不填使用默认URL"
        })
          .then(({ value }) => {
            api
              .push({
                id: params.row.id,
                url: value
              })
              .then(() => {
                ElMessage.success("操作成功");
                search();
              });
          })
          .catch(() => {});
      }
    },
    {
      text: "结束重试",
      show: (row: any) => row.notifyStatus === 2,
      props: {
        type: "danger"
      },
      confirm: {
        // @ts-ignore
        popconfirmProps: {
          width: 150,
          icon: WarnTriangleFilled,
          iconColor: "red"
        },
        message: _ => `确定要结束重试吗？`
      },
      onConfirm(params: ButtonsCallBackParams) {
        api.end(params.row).then(() => {
          ElMessage.success("操作成功");
          search();
        });
      }
    }
  ];

  // ========= dialog form =========

  // 弹窗显示
  const dlgShow = ref(false);
  const dlgTitle = ref("");
  // 表单值
  const editFormDataGen = () => {
    return {
      appId: "",
      apiName: "",
      apiVersion: "",
      lastSendTime: "",
      nextSendTime: "",
      sendMax: "",
      sendCnt: "",
      content: "",
      notifyStatus: "",
      errorMsg: "",
      remark: ""
    };
  };
  const editFormData = ref<any>(editFormDataGen());
  const editFormRules = {
    appId: [{ required: true, message: "请输入app_id" }],
    apiName: [{ required: true, message: "请输入api_name" }],
    apiVersion: [{ required: true, message: "请输入api_version" }]
  };

  // 表单内容
  const editFormColumns: PlusColumn[] = [
    {
      label: "app_id",
      prop: "appId",
      valueType: "input"
    },
    {
      label: "api_name",
      prop: "apiName",
      valueType: "input"
    },
    {
      label: "api_version",
      prop: "apiVersion",
      valueType: "input"
    },
    {
      label: "最近一次发送时间",
      prop: "lastSendTime",
      valueType: "input"
    },
    {
      label: "下一次发送时间",
      prop: "nextSendTime",
      valueType: "input"
    },
    {
      label: "已发送次数",
      prop: "sendCnt",
      valueType: "input"
    },
    {
      label: "发送内容",
      prop: "content",
      valueType: "input"
    },
    {
      label: "状态,1-发送成功,2-发送失败,3-重试结束",
      prop: "notifyStatus",
      valueType: "input"
    },
    {
      label: "失败原因",
      prop: "errorMsg",
      valueType: "input"
    },
    {
      label: "备注",
      prop: "remark",
      valueType: "input"
    }
  ];

  // ========= event =========

  // 添加按钮事件
  const handleAdd = () => {
    isAdd.value = true;
    editFormData.value = editFormDataGen();
    dlgTitle.value = "新增";
    dlgShow.value = true;
  };

  // 保存按钮事件,校验成功后触发
  const handleSave = () => {
    const postData = editFormData.value;
    const pms = isAdd.value ? api.add(postData) : api.update(postData);
    pms.then(() => {
      ElMessage.success("保存成功");
      dlgShow.value = false;
      search();
    });
  };

  // 点击查询按钮
  const handleSearch = () => {
    pageInfo.value.page = 1;
    search();
  };

  // 分页事件
  const handlePaginationChange = (_pageInfo: PageInfo): void => {
    pageInfo.value = _pageInfo;
    search();
  };

  // 查询
  const search = async () => {
    try {
      const { data } = await doSearch();
      tableData.value = data.list;
      total.value = data.total;
    } catch (error) {}
  };
  // 请求接口
  const doSearch = async () => {
    // 查询参数
    const data = searchFormData.value;
    // 添加分页参数
    data.pageIndex = pageInfo.value.page;
    data.pageSize = pageInfo.value.pageSize;

    return api.page(data);
  };

  onMounted(() => {
    // 页面加载
    search();
  });

  function viewContent(row: any) {
    ElMessageBox.alert(
      `<textarea style="width: 400px;height: 300px;" readonly>${row.content}</textarea>`,
      "发送内容",
      {
        dangerouslyUseHTMLString: true
      }
    );
  }

  return {
    actionButtons,
    dlgShow,
    dlgTitle,
    editFormColumns,
    editFormData,
    editFormRules,
    handleAdd,
    handlePaginationChange,
    handleSave,
    handleSearch,
    pageInfo,
    searchFormColumns,
    searchFormData,
    tableColumns,
    tableData,
    total,
    viewContent
  };
}
